// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StocksTableDetail from './StocksTableDetail';
import PositionRuiOptionsModal from './PositionRuiOptionsModal';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './PositionRuiStocksTable.less';

// 图片

// 算式

/* 切割日期 */
function StringSplit(date) {
  // 日期
  if (typeof date === 'string') {
    return date.split(' ')[0];
  }
  return null;
}

/* 财报日剩余对比 */
function DateDiffResults(sDate2) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof sDate2 === 'string') {
    let aDate;
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = new Date(); // 转换为yyyy-MM-dd格式
    aDate = sDate2.split('/');
    oDate2 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 950 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
    return iDays; // 返回相差天数
  }
  return '暂无数据';
}
function DateStamp(param) {
  // sDate1和sDate2是yyyy-MM-dd格式
  const str = param.replace(/-/g, '/');
  const date = new Date(str);
  date.setDate(date.getDate() + 1);
  return date;
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ positionrui, loading }) => ({
  positionrui,
  loading: loading.models.positionruiRule,
}))
@Form.create()
class PositionRuiStocksTable extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:表头
   */

  getColumns() {
    const {
      positionrui: { stocksFilters },
    } = this.props;
    const sourceperson = stocksFilters.sourceperson.map(i => {
      return { text: i, value: i };
    });
    const industry = stocksFilters.industry.map(i => {
      return { text: i, value: i };
    });
    this.setState({
      columns: [
        {
          title: '股票代码',
          width: 130,
          fixed: 'left',
          dataIndex: 'stock',
          sorter: (a, b) => {
            const c = [a.stock, b.stock].sort();
            if (c[0] === a.stock) {
              return 1;
            }
            return -1;
          },
          ...this.getColumnSearchProps('stock'),
        },
        {
          title: 'ID',
          sorter: (a, b) => a.id - b.id,
          dataIndex: 'id',
        },
        {
          title: '公司名称',
          width: 120,
          dataIndex: 'companyname',
          ...this.getColumnSearchProps('companyname'),
        },
        {
          title: '所属人',
          width: 120,
          filters: sourceperson,
          onFilter: (value, record) => {
            return record.sourceperson === null ? false : record.sourceperson.includes(value);
          },
          dataIndex: 'sourceperson',
          render: (value, row, index) => {
            return (
              <span>
                {row.groupname === '空' ? (
                  value !== '空' ? (
                    (value || '').toString()
                  ) : (
                    <Select
                      style={{ width: '100%' }}
                      onChange={this.updateSourceperson.bind(this, row)}
                    >
                      <Option value="金融团队管理">金融团队管理</Option>
                      <Option value="傅总管理">傅总管理</Option>
                      <Option value="郭老师管理">郭老师管理</Option>
                    </Select>
                  )
                ) : (
                  row.groupname.toString()
                )}
              </span>
            );
          },
        },
        {
          title: '行业',
          width: 100,
          filters: industry,
          onFilter: (value, record) => {
            return record.industry === null ? false : record.industry.includes(value);
          },
          dataIndex: 'industry',
        },
        {
          title: '账上可用总股数',
          width: 100,
          sorter: (a, b) => a.lastscnum - b.lastscnum,
          dataIndex: 'lastscnum',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '',
          width: 80,
          dataIndex: 'param1',
        },
        {
          title: '股票价格',
          width: 80,
          dataIndex: 'stockprice',
          sorter: (a, b) => a.stockprice - b.stockprice,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '股数',
          width: 100,
          dataIndex: 'amount',
          sorter: (a, b) => a.amount - b.amount,
          render: (value, row, index) => {
            return (
              <span>
                {row.groupname === '空'
                  ? NumberDivide(value || ''.toString())
                  : NumberDivide(row.stockbelongnumber.toString())}
              </span>
            );
          },
        },
        {
          title: 'No. of Shares',
          width: 80,
          sorter: (a, b) => a.noofshares - b.noofshares,
          dataIndex: 'noofshares',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Sell Put',
          width: 80,
          sorter: (a, b) => a.sellput - b.sellput,
          dataIndex: 'sellput',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Sell Put Exposure',
          width: 80,
          dataIndex: 'sellputexposure',
          sorter: (a, b) => a.sellputexposure - b.sellputexposure,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'AQ',
          width: 80,
          dataIndex: 'aq',
          sorter: (a, b) => a.aq - b.aq,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'AQ Exposure',
          width: 80,
          dataIndex: 'aqexposure',
          sorter: (a, b) => a.aqexposure - b.aqexposure,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '在手股数',
          width: 100,
          dataIndex: 'stocknumber',
          sorter: (a, b) => a.stocknumber - b.stocknumber,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '',
          width: 80,
          dataIndex: 'param2',
          sorter: (a, b) => a.param2 - b.param2,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '2 APA',
          width: 80,
          dataIndex: 'apa2',
          sorter: (a, b) => a.apa2 - b.apa2,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '3 DAC',
          width: 80,
          dataIndex: 'dac3',
          sorter: (a, b) => a.dac3 - b.dac3,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Cost',
          width: 80,
          dataIndex: 'costprice',
          sorter: (a, b) => a.costprice - b.costprice,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Profit',
          width: 80,
          dataIndex: 'profit',
          sorter: (a, b) => a.profit - b.profit,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'ProfitShares',
          width: 90,
          dataIndex: 'profitshares',
          sorter: (a, b) => a.profitshares - b.profitshares,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '在手总值',
          width: 100,
          dataIndex: 'stockonhandvalue',
          sorter: (a, b) => a.stockonhandvalue - b.stockonhandvalue,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Sell Call',
          width: 80,
          dataIndex: 'sellcall',
          sorter: (a, b) => a.sellcall - b.sellcall,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'DQ',
          width: 80,
          dataIndex: 'dq',
          sorter: (a, b) => a.dq - b.dq,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: 'Size',
          width: 80,
          dataIndex: 'size',
          sorter: (a, b) => a.size - b.size,
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '操作',
          width: 70,
          fixed: 'right',
          render: (value, row, index) => <a onClick={this.changeRecord.bind(this, value)}>拆分</a>,
        },
      ],
    });
  }

  changeRecord(record) {
    this.setState({
      record,
      StocksDetailVisible: true,
    });
  }

  closeRecord() {
    const { dispatch } = this.props;
    this.setState(
      {
        StocksDetailVisible: false,
      },
      () => {
        /* 导入列表数据 */
        dispatch({
          type: 'positionrui/GetLastDayPositionStocks',
          payload: {},
        });
      }
    );
  }

  closeOption() {
    const { dispatch } = this.props;
    this.setState({
      OptionVisible: false,
    });
  }

  updateSourceperson(row, value) {
    const { dispatch } = this.props;
    dispatch({
      type: 'positionrui/AddPositionSource',
      payload: {
        sourceperson: value,
        stock: row.stock,
      },
      callback: () => {
        dispatch({
          type: 'positionrui/GetLastDayPositionStocks',
          payload: {},
        });
      },
    });
  }

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const that = this;
    const {
      loading,
      positionrui: { stocks },
    } = this.props;
    const {
      listLoading,
      selectedRows,
      record,
      StocksDetailVisible,
      columns,
      OptionVisible,
    } = this.state;
    if (columns.length === 0 && stocks.code === 1) {
      this.getColumns();
    }
    return (
      <PageHeaderWrapper title="瑞银股票">
        <Card>
          {stocks.code === 0 ? (
            <Loading />
          ) : (
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={stocks}
              pagination={false}
              columns={columns}
              style={{ tableLayout: 'fixed' }}
              className={styles.TableLayout}
              scroll={{ x: 2300, y: 618 }}
              rowKey="id"
              onRow={record => {
                const records = record;
                return {
                  onDoubleClick: event => {
                    that.setState({
                      record: records,
                      OptionVisible: true,
                    });
                  },
                };
              }}
            />
          )}
          <StocksTableDetail
            record={record}
            StocksDetailVisible={StocksDetailVisible}
            closeRecord={this.closeRecord.bind(this)}
          />
          <PositionRuiOptionsModal
            record={record}
            OptionVisible={OptionVisible}
            closeOption={this.closeOption.bind(this)}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'positionrui/GetLastDayPositionStocks',
      payload: {},
      callback: res => {},
    });
  }

  componentWillUnmount() {}
}

export default PositionRuiStocksTable;
